#include <57header.h>

int main(int argc,char*argv[])
{

    int socket_pair_fd[2];
    socketpair(AF_LOCAL, SOCK_STREAM, 0, socket_pair_fd);

    if(fork() == 0){
        // 子进程
        // 读 -> 0读
        close(socket_pair_fd[1]);


        struct msghdr msg;
        bzero(&msg, sizeof(msg));

        char buf[60] = {0};
        struct iovec iovs[1];
        iovs[0].iov_base = buf;
        iovs[0].iov_len = sizeof(buf);

        msg.msg_iov = iovs;
        msg.msg_iovlen = 1;

        struct cmsghdr * cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
        cms->cmsg_len = CMSG_LEN(sizeof(int));
        cms->cmsg_level = SOL_SOCKET;
        cms->cmsg_type = SCM_RIGHTS;
        
        msg.msg_control = cms;
        msg.msg_controllen = CMSG_LEN(sizeof(int));
        
        int ret = recvmsg(socket_pair_fd[0], &msg, 0);
        ERROR_CHECK(ret, -1, "recvmsg");

        void *p = CMSG_DATA(cms);
        int *p_net_fd = (int *)p;

        printf("son: net_fd:  %d \n", *p_net_fd);

        send(*p_net_fd, "hello", 5, 0);


    }else{
        // 父进程
        // 写 -> 1写
        close(socket_pair_fd[0]);

        int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
        char *port = "8080";
        char *ip = "192.168.106.129";
        struct sockaddr_in sockaddr;
        sockaddr.sin_family = AF_INET;
        sockaddr.sin_port = htons(atoi(port));
        sockaddr.sin_addr.s_addr = inet_addr(ip);
        bind(socket_fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
        listen(socket_fd, 10);
        int net_fd = accept(socket_fd, NULL, NULL);

        printf("main: net_fd:  %d \n", net_fd);

        struct msghdr msg;
        bzero(&msg, sizeof(msg));

        char *str = "hello";
        struct iovec iovs[1];
        iovs[0].iov_base = str;
        iovs[0].iov_len = strlen(str);

        msg.msg_iov = iovs;
        msg.msg_iovlen = 1;

        struct cmsghdr * cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
        cms->cmsg_len = CMSG_LEN(sizeof(int));
        cms->cmsg_level = SOL_SOCKET;
        cms->cmsg_type = SCM_RIGHTS;
        void *p = CMSG_DATA(cms);
        int *pfd = (int *)p;
        *pfd = net_fd;
        

        msg.msg_control = cms;
        msg.msg_controllen = CMSG_LEN(sizeof(int));

        // 发送数据
        int ret = sendmsg(socket_pair_fd[1], &msg, 0);
        ERROR_CHECK(ret, -1, "sendmsg");
    }

    return 0;
}

